package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Class;
import cn.wolfcode.crm.domain.ClientLost;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.domain.StudentObserve;
import cn.wolfcode.crm.domain.StudentOfficial;
import cn.wolfcode.crm.mapper.ClientLostMapper;
import cn.wolfcode.crm.mapper.StudentObserveMapper;
import cn.wolfcode.crm.mapper.StudentOfficialMapper;
import cn.wolfcode.crm.query.StudentOfficialQueryObject;
import cn.wolfcode.crm.service.IStudentOfficialService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class StudentOfficialServiceImpl implements IStudentOfficialService {

    @Autowired
    private StudentOfficialMapper studentOfficialMapper;
    @Autowired
    private ClientLostMapper clientLostMapper;
    @Autowired
    private StudentObserveMapper studentObserveMapper;

    @Override
    public void deleteByPrimaryKey(Long id) {
        studentOfficialMapper.deleteByPrimaryKey(id);
    }

    //学员休学
    @Override
    public void change2quit(Long id) {
        studentOfficialMapper.change2quit(id);
    }

    //学员流失
    @Override
    // public void change2lost(Long id) {
    public void change2lost(ClientLost cl) {
        studentOfficialMapper.change2lost(cl);

        //学员流失后,流失管理新增学员信息
        Employee employee = (Employee) SecurityUtils.getSubject().getPrincipal();
        StudentOfficial client = studentOfficialMapper.selectByPrimaryKey(cl.getId());
        ClientLost clientLost = new ClientLost();

        if (client.getClassname() != null) {
            clientLost.setClassname(client.getClassname().getName());
        }
        if (client.getSaleman() != null) {
            clientLost.setSale(client.getSaleman().getUsername());
        }
        if (client.getClientName() != null) {
            clientLost.setTel(client.getClientName().getTel());
            clientLost.setClientName(client.getClientName().getName());
        }
        if (client.getClientName() != null) {
            clientLost.setClient_id(client.getClientName().getId());
        }
        clientLost.setChecker(employee.getUsername());
        clientLost.setLostdate(new Date());
        clientLost.setState(false);
        //插入前端传入的参数
        if (cl.getReturnOrNot() != null) {
            clientLost.setReturnOrNot(cl.getReturnOrNot());
        }
        if (cl.getLoststep() != null) {
            clientLost.setLoststep(cl.getLoststep());
        }
        if (cl.getDrawBackAmount() != null) {
            clientLost.setDrawBackAmount(cl.getDrawBackAmount());
        }
        if (cl.getLostcause() != null) {
            clientLost.setLostcause(cl.getLostcause());
        }

        clientLostMapper.insert(clientLost);
    }

    //学员换班
    @Override
    public void change2class(Long id,Long newclassId) {
        studentOfficialMapper.change2class(id);
        //学员转班更改状态,新增学员升班留级表数据
        StudentOfficial studentOfficial = studentOfficialMapper.selectByPrimaryKey(id);

        StudentObserve studentObserve = new StudentObserve();
        Class newclass = new Class();
        newclass.setId(newclassId);

        studentObserve.setNewClass(newclass);
        studentObserve.setClient(studentOfficial.getClientName());
        studentObserve.setOldClass(studentOfficial.getClassname());
        studentObserve.setPayfit(studentOfficial.getPayFit());
        studentObserve.setSaleUser(studentOfficial.getSaleman());
        studentObserve.setState(false);
        studentObserve.setStateDate(new Date());
        studentObserve.setTel(studentOfficial.getTel());
        studentObserve.setTotalAmount(studentOfficial.getTotalAmount());
        studentObserve.setWaitngfit(studentOfficial.getWaitingFit());
        System.out.println(studentObserve);
        studentObserveMapper.insert(studentObserve);
    }

    @Override
    public void saveOrUpdate(StudentOfficial entity) {
        System.out.println(entity.getId());
        if(entity.getId() != null){
            BigDecimal totalAmount = entity.getTotalAmount();
            BigDecimal payFit = entity.getPayFit();
            BigDecimal waitingFit = entity.getWaitingFit();
            if(payFit.add(waitingFit).compareTo(totalAmount) == 1){
                throw new RuntimeException("需付款金额大于或小于总金额");
            }
            if (payFit.compareTo(totalAmount) == 0){
                entity.setPayState(true);
                studentOfficialMapper.updateByPrimaryKey(entity);
            }else{
                entity.setPayState(false);
                studentOfficialMapper.updateByPrimaryKey(entity);
            }
        }else {
            studentOfficialMapper.insert(entity);
        }
    }

    @Override
    public StudentOfficial selectByPrimaryKey(Long id) {
        StudentOfficial key = studentOfficialMapper.selectByPrimaryKey(id);
        return key;
    }

    @Override
    public PageResult query(StudentOfficialQueryObject qo) {

        int total = studentOfficialMapper.queryForCount(qo);
        if (total == 0) {
            return PageResult.PAGERESULT_EMPTY;
        }
        List<StudentOfficial> query = studentOfficialMapper.query(qo);
        return new PageResult(total,query);
    }

    //查询正式学员欠款金额
    @Override
    public StudentOfficial getOwnTuitionByClientId(Long id) {
        return studentOfficialMapper.getOwnTuitionByClientId(id);
    }


    @Override
    public List<StudentOfficial> selectAll() {
        return studentOfficialMapper.selectAll();
    }


    /**
     * 根据学生信息发送短信催缴学费
     *
     * @param studentOfficial
     */
    public int sengMsg(StudentOfficial studentOfficial) throws IOException {
        /*
         * model
         * 尊敬的xxx学员，您所在的xxx班级，已付学费xxx元，还欠学费xxx元，请在最后付款时间xxxx前来缴纳
         * */
        StringBuilder builder = new StringBuilder();

        String name = studentOfficial.getClientName().getName();
        String classname = studentOfficial.getClassname().getName();
        String payFit = studentOfficial.getPayFit().toString();
        String waitFit = studentOfficial.getWaitingFit().toString();

        builder.append("尊敬的 ").append(name).append(" 学员").append("您所在的班级:").append(classname);
//        if (payFit != null && payFit != "") {
//            builder.append("已付金额:").append(payFit);
//        }
//        builder.append("还欠金额:").append(waitFit);
        if (studentOfficial.getLastPaymentDate() != null) {
            String lastPaymentDate = studentOfficial.getLastPaymentDate().toString();
            builder.append("请在最后时间").append(lastPaymentDate).append("caina");
        }

        //短信内容
        String text = builder.toString();
        //手机号码
        String tel = studentOfficial.getTel();

        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://utf8.api.smschinese.cn");
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");//在头文件中设置转码
        NameValuePair[] data = {new NameValuePair("Uid", "cuixuhui"), new NameValuePair("Key", "d41d8cd98f00b204e980"),
                new NameValuePair("smsMob", tel), new NameValuePair("smsText", text)};
        post.setRequestBody(data);

        client.executeMethod(post);
        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:" + statusCode);
        for (Header h : headers) {
            System.out.println(h.toString());
        }
        String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        System.out.println(result); //打印返回消息状态

        post.releaseConnection();

        return statusCode;
    }


    /**
     * 根据条件导出到exl
     *
     * @param qo
     * @return
     */
    @Override
    public Workbook exportXls(StudentOfficialQueryObject qo) {
        //创建xls
        Workbook book = new HSSFWorkbook();
        //创建工作簿
        Sheet sheet = book.createSheet();
        //设置第一行的标题
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("学员名称");
        row.createCell(1).setCellValue("销售名称");
        row.createCell(2).setCellValue("总学费");
        row.createCell(3).setCellValue("待缴学费");
        row.createCell(4).setCellValue("缴费状态");
        row.createCell(5).setCellValue("入学时间");
        row.createCell(6).setCellValue("学校");
        row.createCell(7).setCellValue("电话");
        row.createCell(8).setCellValue("所在班级");
        row.createCell(9).setCellValue("付款方式");
        row.createCell(10).setCellValue("类型");
        row.createCell(11).setCellValue("状态");

        List<?> list = studentOfficialMapper.query(qo);

        for (int i = 0; i < list.size(); i++) {
            try {
                StudentOfficial studentOfficial = (StudentOfficial) list.get(i);
                //创建行
                row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(studentOfficial.getClientName() == null ? "" : studentOfficial.getClientName().getName());
                row.createCell(1).setCellValue(studentOfficial.getSaleman() != null ? studentOfficial.getSaleman().getUsername() : "");
                row.createCell(2).setCellValue(studentOfficial.getTotalAmount().toString());
                row.createCell(3).setCellValue(studentOfficial.getWaitingFit().toString());
                row.createCell(4).setCellValue(studentOfficial.getPayState() ? "已付" : "未付");
                row.createCell(5).setCellValue(studentOfficial.getAdmissionDate()!=null?studentOfficial.getAdmissionDate().toString():"");
                row.createCell(6).setCellValue(studentOfficial.getSchool());
                row.createCell(7).setCellValue(studentOfficial.getTel());
                row.createCell(8).setCellValue(studentOfficial.getClassname() != null ? studentOfficial.getClassname().getName() : "");
                row.createCell(9).setCellValue(studentOfficial.getPayType() != null ? studentOfficial.getPayType().getName() : "");
                row.createCell(10).setCellValue(studentOfficial.getClientType() != null ? studentOfficial.getClientType().getName() : "");
                row.createCell(11).setCellValue(studentOfficial.getClientState() != null ? studentOfficial.getClientState().getName() : "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return book;
    }
}
